<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-900">
    <div class="w-full max-w-md">
      <div class="bg-gray-800 rounded-lg shadow-xl p-8">
        <h2 class="text-3xl font-bold text-center text-white mb-8">登录</h2>

        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          @submit.prevent
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              size="large"
              prefix-icon="User"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              size="large"
              prefix-icon="Lock"
              show-password
              @keyup.enter="handleLogin"
            />
          </el-form-item>

          <el-form-item prop="code" v-if="captchaEnabled">
            <el-row :gutter="20">
              <el-col :span="16">
                <el-input
                  v-model="loginForm.code"
                  placeholder="请输入验证码"
                  size="large"
                  @keyup.enter="handleLogin"
                />
              </el-col>
              <el-col :span="8">
                <img
                  :src="captchaUrl"
                  @click="getCaptcha"
                  class="cursor-pointer h-[40px] w-full"
                  alt="验证码"
                />
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item>
            <el-checkbox v-model="rememberMe">记住密码</el-checkbox>
            <NuxtLink to="/forget" class="float-right text-green-400 hover:text-green-300">
              忘记密码？
            </NuxtLink>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              size="large"
              class="w-full"
              :loading="loading"
              @click="handleLogin"
            >
              登 录
            </el-button>
          </el-form-item>

          <div class="text-center text-gray-400">
            还没有账号？
            <NuxtLink to="/register" class="text-green-400 hover:text-green-300">
              立即注册
            </NuxtLink>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

const siteConfig = useSiteConfig()

// SEO设置
useSeoMeta({
  title: '登录',
  description: `登录${siteConfig.siteName}账号`
})

const loginFormRef = ref<FormInstance>()
const loading = ref(false)
const captchaEnabled = ref(false)
const rememberMe = ref(false)
const captchaUrl = ref('')

const loginForm = reactive({
  username: '',
  password: '',
  code: '',
  uuid: ''
})

const loginRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

// 获取验证码
const getCaptcha = async () => {
  const { data } = await $fetch('/dev-api/captchaImage')
  if (data.value) {
    captchaEnabled.value = data.value.captchaEnabled === true
    if (captchaEnabled.value) {
      captchaUrl.value = 'data:image/gif;base64,' + data.value.img
      loginForm.uuid = data.value.uuid
    }
  }
}

// 登录
const handleLogin = async () => {
  const valid = await loginFormRef.value?.validate()
  if (!valid) return

  loading.value = true
  try {
    // 调用若依框架的登录接口
    const { data } = await $fetch('/dev-api/login', {
      method: 'POST',
      body: loginForm
    })

    if (data.value?.token) {
      // 保存token
      const token = useCookie('Admin-Token')
      token.value = data.value.token

      // 如果记住密码，保存到本地
      if (rememberMe.value) {
        localStorage.setItem('username', loginForm.username)
      }

      ElMessage.success('登录成功')
      await navigateTo('/')
    }
  } catch (error: any) {
    ElMessage.error(error.message || '登录失败')
    // 刷新验证码
    if (captchaEnabled.value) {
      getCaptcha()
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  // 获取验证码
  getCaptcha()

  // 如果记住了用户名，自动填充
  const savedUsername = localStorage.getItem('username')
  if (savedUsername) {
    loginForm.username = savedUsername
    rememberMe.value = true
  }
})
</script>

<style scoped>
:deep(.el-input__wrapper) {
  background-color: rgba(31, 41, 55, 0.5);
}

:deep(.el-input__inner) {
  color: white;
}
</style>